package cn.itrip.trade.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.trade.service.OrderService;
import cn.itrip.utlis.Constants;
import cn.itrip.utlis.DtoUtil;
import com.github.wxpay.sdk.MyConfig;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description :
 * Created by Li on 2021-01-06 13:40:48
 */
@Slf4j
@RestController
@RequestMapping("/api/wxpay")
public class WxpayController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private MyConfig config;
    /**
     * 生成二维码
     * @param orderNo
     * @return
     */
    @GetMapping("/createqccode/{orderNo}")
    public Dto createqccode(@PathVariable String orderNo){
        ItripHotelOrder order = orderService.findByOrderNo(orderNo);
        if (order == null || !order.getOrderStatus().equals(Constants.ORDER_STATUS_WAIT_PAY)) {
            return DtoUtil.returnFail("订单状态异常","500001");
        }
        WXPay wxpay = null;
        try {
            wxpay = new WXPay(config);
        } catch (Exception e) {
            log.error("微信支付初始化失败", e);
            return DtoUtil.returnFail("微信支付初始化失败","500001");
        }

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "爱旅行订单支付");
        data.put("out_trade_no", orderNo);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        //一分钱
        data.put("total_fee", "1");
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", config.getNotifyUrl());
        data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
        data.put("product_id", order.getId()+"");

        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            if(log.isDebugEnabled()){
                log.debug("{}",resp);
            }
            String returnCode = resp.get("return_code");
            if(returnCode.equals("SUCCESS")){
                Map<String, String> result = new HashMap<>();
                result.put("codeUrl", resp.get("code_url"));
                result.put("payAmount", order.getPayAmount()+"");
                return DtoUtil.returnDataSuccess(result);
            }
        } catch (Exception e) {
            log.error("生成二维码异常", e);
        }
        return DtoUtil.returnFail("生成二维码失败","500002");
    }

    @PostMapping("/notify")
    public void notify(HttpServletRequest request, HttpServletResponse response){
        //支付结果通知的xml格式数据
        String notifyData = parseWxpayResult(request);
        if(notifyData.length()!=0){
            WXPay wxpay = null;
            try {
                wxpay = new WXPay(config);
            } catch (Exception e) {
                log.error("初始化微信支付失败",e);
            }
            try{
                Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);
                if(log.isDebugEnabled()){
                    log.debug("微信支付结果{}",notifyData);
                }
                if(wxpay.isResponseSignatureValid(notifyMap)){
                    String returnCode = notifyMap.get("return_code");
                    if("SUCCESS".equals(returnCode)){
                        String tradeNo = notifyMap.get("transaction_id");
                        String orderNo = notifyMap.get("out_trade_no");
                        //String totalFee = notifyMap.get("total_fee");
                        //修改订单状态
                        if(orderService.isProcessed(orderNo,tradeNo)){
                            orderService.paySuccess(orderNo,tradeNo);
                        }
                        //响应微信，不要再异步通知了
                        Map<String,String> result = new HashMap<>();
                        result.put("return_code","SUCCESS");
                        result.put("return_msg","OK");
                        PrintWriter out = response.getWriter();
                        out.print(WXPayUtil.mapToXml(result));
                        out.close();
                    }//240  360  400  ==  1000  ==  25*40  ==  1000  5+12+13+10
                }else {
                    log.error("微信签名错误");
                }
            }catch (Exception e){
                log.error("微信支付异常",e);
            }
        }
    }


    @GetMapping("/queryorderstatus/{orderNo}")
    public Dto queryorderstatus(@PathVariable String orderNo) {
        return DtoUtil.returnDataSuccess(orderService.findByOrderNo(orderNo));
    }

    private String parseWxpayResult(HttpServletRequest request) {
        StringBuffer xml = new StringBuffer();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"))){
            String line = null;
            while ((line = in.readLine()) != null) {
                xml.append(line);
            }
        } catch (Exception e) {
            log.error("解析微信支付结果异常" ,e);
            xml.setLength(0);
        }
        return xml.toString();
    }
}
